package com.moyun.service.system;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moyun.common.aspect.BusinessType;
import com.moyun.common.annotation.OperLog;
import com.moyun.model.po.system.SysUserEntity;
import com.moyun.mapper.system.SysRoleMapper;
import com.moyun.mapper.system.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * <h3>learning_route</h3>
 * <p>用户所有信息类</p>
 *
 * @author : ybx
 * @date : 2020-12-30 10:19:50
 **/
@Service
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    @OperLog(operModul = "登录模块", operType = BusinessType.LOGIN, operDesc = "登录系统")
    public UserDetails loadUserByUsername(String username) {
        // 根据用户名，从数据库中获取数据。查看是否有该用户信息
        SysUserEntity user = userMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name", username));
        // 用户不存在，则抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询用户对应的角色信息以及权限 (使用数据库中 sys_role 系统组织角色表)
//        user = this.userMapper.selectUserWithRolesByUserId(user.getId());
        // 查询用户对应的角色信息以及权限 (使用数据库中 sys_org_role 系统组织角色表)
        user = this.userMapper.selectUserWithOrgRolesByUserId(user.getId());
        log.info("进入到MyUserDetailsService(自定义用户信息认证服务)中,进行用户身份认证");
        return user;
    }
}
